let controller = require("./controller");
let mydebug = require('./mydebug');
let moment = require('moment');

let current_pwm = [100, 100, 100];

let timeslots = [
    {t: "00:00", pwm : [0, 0, 0]},
    {t: "05:59", pwm : [0, 0, 0]},
    {t: "06:00", pwm : [5, 5, 5]},
    {t: "07:00", pwm : [20, 20, 20]},
    {t: "10:00", pwm : [150, 150, 150]},
    {t: "12:00", pwm : [200, 200, 200]},
    {t: "13:00", pwm : [300, 300, 300]},
    {t: "14:00", pwm : [300, 300, 300]},
    {t: "16:00", pwm : [220, 220, 220]},
    {t: "17:00", pwm : [200, 200, 200]},
    {t: "18:00", pwm : [150, 150, 150]},
    {t: "19:00", pwm : [50, 50, 50]},
    {t: "20:00", pwm : [10, 50, 10]},
    {t: "21:00", pwm : [0, 25, 0]},
    {t: "22:00", pwm : [0, 5, 0]},
    {t: "23:00", pwm : [0, 0, 0]},
    {t: "24:00", pwm : [0, 0, 0]}
];

function pwm2Lux(pwm) {
    // TODO: need a table for transformate
    return Math.round(pwm);
}

function calculatePwm(p1, p2, progress) {
    let pwm = 0;

    pwm = (p2 - p1) * progress;
    
    return pwm + p1;
}

function calculate(slot, progress) {
    let luxs = [0, 0, 0];

    for (i = 0; i < 3; i++) {
        pwm = calculatePwm(timeslots[slot].pwm[i], timeslots[slot + 1].pwm[i], progress);
        luxs[i] = pwm2Lux(pwm);
    }

    return luxs;
}

function toISODate(t) {
    let m = moment(t);
    return m.format("YYYY-MM-DD");
}

function setLEDpwm() {
    let now = new Date();
    for (i = 0; i < timeslots.length - 1; i++) {
        d = toISODate(now);
        t1 = moment(d + " " + timeslots[i].t);
        t2 = moment(d + " " + timeslots[i + 1].t);

        // Check time
        if ((now >= t1) && (now < t2)) {
            // [i, i+1) is correct timeslot
            mydebug.LogOutput("Now is timeslot:", timeslots[i].t);
            
            slotMinutes = moment.duration(t2 - t1);
            progressMinutes = moment.duration(now - t1);
            
            luxs = calculate(i, progressMinutes / slotMinutes);
            mydebug.LogOutput(luxs);

            // Set to hardware
            for (i = 0; i < 3; i++) {
                controller.setLEDpwm(i, luxs[i]);
            }

            return;
        }
    }
}

controller.controllerEvent.on('connect', function() {
    mydebug.LogOutput("Restore light pwm.")
    // restore
    setLEDpwm();
})

setInterval(function() {
    setLEDpwm();
}, 30000);


controller.controllerEvent.on('disconnect', function() {

})
